package com.um.springboot.starter.controller;

import cn.hutool.core.util.StrUtil;
import com.um.springboot.starter.code.CommonCode;
import com.um.springboot.starter.entity.AppSTS;
import com.um.springboot.starter.entity.STS;
import com.um.springboot.starter.helper.SessionHelper;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.properties.HshProperties;
import com.um.springboot.starter.service.STSService;
import com.um.springboot.starter.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author 邓南辉
 * 日期 2020/8/7
 * 版权所有 广州优匠科技有限公司
 */
@Api(tags = "文件")
@RestController
@RequestMapping("/api/v1/sts")
public class STSController {

    @Autowired
    STSService stsService;

    @Autowired
    HshProperties hshProperties;

    @Autowired
    SessionHelper sessionHelper;

    @ApiOperation(value = "获取OSS上传Token")
    @GetMapping("/token")
    public Response<STS> getStsToken() {
        if (!hshProperties.getFile().isAllowUpload()) {
            return Response.failed(CommonCode.NotOpen);
        }
        if (!hshProperties.getFile().isAllowAnonymousUpload() && StrUtil.isBlank(sessionHelper.getSessionUserId())) {
            return Response.failed(CommonCode.LoginExpired);
        }

        STS sts = stsService.getStsToken();
        return Response.success(sts);
    }

    @PostMapping("/token")
    public Response<AppSTS> getToken(@RequestBody Map params){
        if (!hshProperties.getFile().isAllowUpload()) {
            return Response.failed(CommonCode.NoApiPermission);
        }
        if (!hshProperties.getFile().isAllowAnonymousUpload() && StrUtil.isBlank(sessionHelper.getSessionUserId())) {
            return Response.failed(CommonCode.LoginExpired);
        }

        String dir = StringUtil.getTrim(params.get("dir"));
        return Response.success(stsService.getAppToken(dir));
    }

}
